#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef struct ListNode 
{
    int val;
    struct ListNode *next;
}ListNode;



ListNode* partition(ListNode* pHead, int x) 
{
    ListNode* head1, * tail1, * prev;
    tail1 = pHead;
    head1 = prev = NULL;
    ListNode* heal2, * tail2;
    heal2 = tail2 = (ListNode*)malloc(sizeof(ListNode));
    assert(heal2);
    tail2->next = NULL;

    while (tail1)
    {
        if (tail1->val < x)
        {
            if (prev)
            {
                prev->next = tail1;
                prev = prev->next;
            }
            else
            {
                head1 = prev = tail1;
            }
        }
        else
        {
            tail2->next = tail1;
            tail2 = tail2->next;
        }
        tail1 = tail1->next;
    }
    tail2->next = NULL;
    if (!prev)
    {
        head1 = heal2->next;
    }
    else
    {
        prev->next = heal2->next;
    }
    return head1;
}



int main()
{
    ListNode* n1 = (ListNode*)malloc(sizeof(ListNode));
    ListNode* n2 = (ListNode*)malloc(sizeof(ListNode));
    ListNode* n3 = (ListNode*)malloc(sizeof(ListNode));
    ListNode* n4 = (ListNode*)malloc(sizeof(ListNode));
    ListNode* n5 = (ListNode*)malloc(sizeof(ListNode));
    ListNode* n6 = (ListNode*)malloc(sizeof(ListNode));
    assert(n1);
    assert(n2);
    assert(n3);
    assert(n4);
    assert(n5);
    assert(n6);
    n1->val = 1;
    n2->val = 5;
    n3->val = 6;
    n4->val = 3;
    n5->val = 4;
    n6->val = 2;

    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n6;
    n6->next = NULL;


    ListNode* ret = partition(n1, 5);
    while (ret)
    {
        printf("%d ", ret->val);
        ret = ret->next;
    }
    printf("NULL\n");
    return 0;
}